package com.team.order.service.impl;

import com.team.order.domain.dto.OrderWithMerchantDTO;
import com.team.order.domain.vo.RegionOrderStatisticsVO;
import com.team.order.mapper.AdminOrderMapper;
import com.team.order.service.OrderStatisticsService;
import com.team.order.utils.GeoToDistrictUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.*;

@Service
@RequiredArgsConstructor
public class OrderStatisticsServiceImpl implements OrderStatisticsService {

    private final AdminOrderMapper orderMapper;
    private final RedisTemplate<String, String> redisTemplate;
    private final GeoToDistrictUtil geoToDistrictUtil;
    // private final RemoteMerchantService remoteMerchantService;

    @Override
    public List<RegionOrderStatisticsVO> getOrderStatsByRegion(String startTime, String endTime) {
        List<OrderWithMerchantDTO> orderList = orderMapper.selectOrdersWithMerchantInfo(startTime, endTime);
        Map<String, RegionOrderStatisticsVO> regionMap = new HashMap<>();

        // 遍历每个订单
        for (OrderWithMerchantDTO order : orderList) {
            Long merchantId = order.getMerchantId();
            String redisKey = "merchant:district:" + merchantId;
            // 从Redis中获取商家的区县信息
            String district = redisTemplate.opsForValue().get(redisKey);
            // 如果Redis中查不到，需要调用API查询区县地址存入Redis
            if (district == null) {
                // 模拟调用商户微服务获取坐标的假数据
                double lng = 113.75 + (merchantId % 5);
                double lat = 34.7 + (merchantId % 3);
                district = geoToDistrictUtil.getDistrictByGeo(lng, lat);
                redisTemplate.opsForValue().set(redisKey, district, Duration.ofDays(7));
            }

            RegionOrderStatisticsVO vo = regionMap.computeIfAbsent(district, RegionOrderStatisticsVO::new);
            // 根据服务类型（维护、护理、洗涤）更新区域的订单统计信息
            switch (order.getServiceTypeId()) {
                case 1 -> vo.incrementMaintenance();
                case 2 -> vo.incrementCare();
                case 3 -> vo.incrementWash();
            }
            // 增加总订单数
            vo.incrementTotal();
        }
        //
        RegionOrderStatisticsVO total = new RegionOrderStatisticsVO("合计", 0, 0, 0, 0);
        //
        for (RegionOrderStatisticsVO vo : regionMap.values()) {
            total.add(vo);
        }
        //
        List<RegionOrderStatisticsVO> result = new ArrayList<>(regionMap.values());
        result.sort(Comparator.comparing(RegionOrderStatisticsVO::getRegionName));
        result.add(0, total);
        return result;
    }
}
